package com.kanshu.ksgb.fastread.doudou.module.bookcity.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.baseadapter.CustomFragmentAdapter;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseFragment;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.ICancelRefreshing;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.ISwitchTab;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.view.tablayout.OnTabSelectListener;
import com.kanshu.ksgb.fastread.doudou.common.view.tablayout.SlidingTabLayout;
import com.kanshu.ksgb.fastread.doudou.module.book.event.ScrollEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.module.personal.event.SexSelectEvent;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by wcy on 2017\6\13
 */
@Route(path = ARouterConfig.HOME_PAGE_BOOK_CITY)
public class AdBookCityFragment extends BaseFragment implements ICancelRefreshing, ISwitchTab {
    public static final int TYPE_TAB_SELECTED = Constants.BookCityTabType.TYPE_SELECTED;
    public static final int TYPE_TAB_MALE = Constants.BookCityTabType.TYPE_MALE;
    public static final int TYPE_TAB_FEMALE = Constants.BookCityTabType.TYPE_FEMALE;
    @BindView(R.id.tab_layout)
    SlidingTabLayout mTabLayout;
    @BindView(R.id.pager)
    ViewPager mPager;
    Unbinder unbinder;
    @BindView(R.id.top)
    FrameLayout mTop;
    int mCurTab = TYPE_TAB_SELECTED;
    @BindView(R.id.search)
    ImageView mSearch;
    @BindView(R.id.top_mask)
    ImageView mTopMask;
    int mSubTabIndex;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_city_layout, null);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    // 3.0.8 需求更改，首次打开书城fragment  根据用户性别显示 此项优先级最高
    private void parseArguments() {
        String loginSex = MMKVUserManager.getInstance().getLoginSex();
        mSubTabIndex = Integer.valueOf(TextUtils.isEmpty(loginSex) ? "0" : loginSex);
    }

    private void init() {
        //适配状态栏
        int statusBarHeight = DisplayUtils.getStatusBarHeight(getActivity());
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mSearch.getLayoutParams();
        params.topMargin = statusBarHeight + DisplayUtils.dip2px(getContext(),14f);
        mSearch.setLayoutParams(params);
        FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) mTabLayout.getLayoutParams();
        p.topMargin = statusBarHeight + DisplayUtils.dip2px(getContext(),12f);
        mTabLayout.setLayoutParams(p);

        parseArguments();
        List<Fragment> list = new ArrayList<>();
        list.add(new AdSelectedFragment());
        list.add(AdMaleOrFemaleFragment.newInstance(Constants.BookCityTabType.TYPE_MALE));
        list.add(AdMaleOrFemaleFragment.newInstance(Constants.BookCityTabType.TYPE_FEMALE));
        String[] strs = new String[]{"精选", "男频", "女频"};
        CustomFragmentAdapter pagerAdapter = new CustomFragmentAdapter(getChildFragmentManager(), list);
        mPager.setAdapter(pagerAdapter);
        mTabLayout.setViewPager(mPager, strs);
        mPager.setOffscreenPageLimit(strs.length);
        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                //埋点统计
                AdPresenter.pvuvStatics(position,R.string.SCTOP_POSITION1, R.string.SCTOP_POSITION2, R.string.SCTOP_POSITION3);
                Fragment fragment = list.get(position);
                if (fragment instanceof BookCityCallListener && ((BookCityCallListener) fragment).getScrollDistance() > 0) {
                    mTop.setBackgroundColor(Color.WHITE);
                    mTopMask.setVisibility(View.GONE);
                    mSearch.setImageResource(R.mipmap.ic_search);
                    mTabLayout.setIndicatorColor(getResources().getColor(R.color.theme));
                    mTabLayout.setTextBold(SlidingTabLayout.TEXT_BOLD_WHEN_SELECT);
                    mTabLayout.setTextSelectColor(Color.parseColor("#333333"));
                    mTabLayout.setTextUnselectColor(Color.parseColor("#999999"));
                } else {
                    mTop.setBackgroundColor(Color.TRANSPARENT);
                    mTopMask.setVisibility(View.VISIBLE);
                    mSearch.setImageResource(R.mipmap.ic_search_white);
                    mTabLayout.setTextBold(SlidingTabLayout.TEXT_BOLD_NONE);
                    mTabLayout.setIndicatorColor(getResources().getColor(R.color.white));
                    mTabLayout.setTextSelectColor(Color.WHITE);
                    mTabLayout.setTextUnselectColor(getResources().getColor(R.color.book_city_tab_unselect_color));
                }
            }

            @Override
            public void onTabReselect(int position) {
                //埋点统计
                AdPresenter.pvuvStatics(position, R.string.SCTOP_POSITION1, R.string.SCTOP_POSITION2, R.string.SCTOP_POSITION3);
            }
        });
        switchTab(mSubTabIndex);
    }
    @Override
    public void switchTab(int tabPos) {
        if (isAdded() && mTabLayout != null && tabPos >= 0) {
            mTabLayout.setCurrentTab(tabPos);
            if (tabPos == TYPE_TAB_SELECTED) {
                ScrollEvent event = new ScrollEvent();
                event.type = TYPE_TAB_SELECTED;
                EventBus.getDefault().post(event);
            }
        }
    }


    @Override
    public void cancel() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    public FrameLayout getTop() {
        return mTop;
    }

    public ImageView getSearch() {
        return mSearch;
    }

    /**
     * 获取顶部遮罩
     * @return
     */
    public ImageView getTopMask() {
        return mTopMask;
    }

    public SlidingTabLayout getTabLayout() {
        return mTabLayout;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleSexEvent(SexSelectEvent event) {
    }


    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
    }


    @OnClick(R.id.search)
    public void onViewClicked() {
        AdPresenter.pvuvStatics(R.string.SCSEARCH);
        ARouterUtils.toActivity(ARouterConfig.SEARCH);
    }

    @OnClick(R.id.top)
    public void onTopClicked() {
    }

    public static AdBookCityFragment newIntance(int subTabIndex) {
        AdBookCityFragment fragment = new AdBookCityFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("sub_tab_index", subTabIndex);
        fragment.setArguments(bundle);
        return fragment;
    }
}
